<template>
  <div class="space-y">
    <div style="display:flex;align-items:center;gap:16px;">
      <button class="btn" @click="goBack">← 返回订单列表</button>
      <h2>订单详情</h2>
    </div>
    
    <div v-if="loading" class="card" style="padding:16px;">加载中...</div>
    
    <div v-else-if="error" class="card" style="padding:16px; color:#ef4444;">{{ error }}</div>
    <div v-else-if="!orderDetail" class="card" style="padding:16px;">无法获取订单详情</div>
    
    <div v-else class="space-y">
      <!-- 订单基本信息 -->
      <div class="card" style="padding:16px;">
        <div class="space-y">
          <div class="row" style="justify-content:space-between;">
            <div>订单号：<b>{{ orderDetail.order.id }}</b></div>
            <div class="price">¥ {{ orderDetail.order.totalAmount }}</div>
          </div>
          
          <!-- 餐厅名称 -->
          <div class="muted">餐厅：{{ restaurant ? restaurant.name : '-' }}</div>
          
          <div class="muted">状态：{{ orderDetail.order.status }}</div>
          <div class="muted">下单时间：{{ formatOrderDate(orderDetail.order.orderDate) }}</div>
          
          <div class="muted">配送地址：{{ orderDetail.order.deliveryAddress }}</div>
          <div class="muted">联系电话：{{ orderDetail.order.contactPhone }}</div>
        </div>
      </div>
      
      <!-- 订单项列表 -->
      <div class="card" style="padding:16px;">
        <h3>商品明细</h3>
        <div v-if="!orderDetail.items || orderDetail.items.length === 0" class="muted">暂无商品</div>
        
        <div v-else class="space-y">
          <div v-for="item in orderDetail.items" :key="item.id" class="row" style="align-items:center;gap:12px;">
            <!-- 商品图片 -->
            <div v-if="item.imageUrl" style="flex-shrink:0;">
              <img :src="item.imageUrl" style="width:60px;height:45px;object-fit:cover;border-radius:4px;" />
            </div>
            <div v-else style="width:60px;height:45px;background-color:#f3f4f6;border-radius:4px;flex-shrink:0;"></div>
            
            <!-- 商品名称 -->
            <div style="flex:1;">{{ item.menuItemName || '商品' }}</div>
            
            <!-- 商品数量和价格 -->
            <div class="row" style="gap:16px;">
              <div>x{{ item.quantity }}</div>
              <div>¥ {{ item.price }}</div>
            </div>
          </div>
          
          <div class="row" style="justify-content:space-between;margin-top:16px;border-top:1px solid #eee;padding-top:8px;">
            <div>总计</div>
            <div class="price">¥ {{ orderDetail.order.totalAmount }}</div>
          </div>
        </div>
      </div>
      
      <!-- 订单操作按钮 -->
      <div v-if="canCancelOrder(orderDetail.order) || canUpdateOrderStatus(orderDetail.order)" class="row" style="justify-content:flex-end; gap: 8px;">
        <button v-if="canCancelOrder(orderDetail.order)" @click="cancelOrder(orderDetail.order.id)" class="btn" style="background-color: #ff4757; color: white;">
          取消订单
        </button>
        <button v-if="canUpdateOrderStatus(orderDetail.order)" @click="updateOrderStatus" class="btn" style="background-color: #2ed573; color: white;">
          {{ isUpdatingStatus ? '更新中...' : '完成订单' }}
        </button>
      </div>

      <!-- 订单评价功能 -->
      <div v-if="canEvaluateOrder(orderDetail.order) && !evaluationSubmitted" class="card" style="padding:16px;">
        <h3>评价订单</h3>
        
        <!-- 评分组件 -->
        <div class="space-y" style="margin-bottom:16px;">
          <label style="display:block;">评分：</label>
          <div class="row" style="gap:8px;">
            <span v-for="star in 5" :key="star" 
                  class="star" 
                  @click="score = star"
                  :style="{ color: star <= score ? '#ffc107' : '#e2e8f0', cursor: 'pointer', fontSize: '24px' }">
              ★
            </span>
          </div>
        </div>
        
        <!-- 评价输入框 -->
        <div class="space-y" style="margin-bottom:16px;">
          <label style="display:block;">评价内容：</label>
          <textarea v-model="evaluate" placeholder="请输入您的评价..." 
                    style="width:100%; padding:8px; border:1px solid #d1d5db; border-radius:4px; min-height:100px;"></textarea>
        </div>
        
        <!-- 提交按钮 -->
        <div class="row" style="justify-content:flex-end;">
          <button @click="submitEvaluation" class="btn primary" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '提交评价' }}
          </button>
        </div>
      </div>

      <!-- 已提交的评价 -->
      <div v-if="orderDetail.order.evaluate && evaluationSubmitted" class="card" style="padding:16px;">
        <h3>您的评价</h3>
        
        <!-- 已评分显示 -->
        <div class="space-y" style="margin-bottom:16px;">
          <label style="display:block;">评分：</label>
          <div class="row" style="gap:8px;">
            <span v-for="star in 5" :key="star" 
                  class="star"
                  :style="{ color: star <= orderDetail.order.score ? '#ffc107' : '#e2e8f0', fontSize: '24px' }">
              ★
            </span>
          </div>
        </div>
        
        <!-- 已评价内容显示 -->
        <div class="space-y">
          <label style="display:block;">评价内容：</label>
          <div style="padding:8px; background-color:#f9fafb; border-radius:4px; min-height:100px;">
            {{ orderDetail.order.evaluate }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
      return {
        orderDetail: null,
        loading: false,
        error: '',
        menuItems: [] // 存储餐厅菜单，用于根据商品名称查询图片
        , restaurant: null // 存储餐厅信息，用于显示餐厅名称
        // 评价相关数据
        , score: 5,
        evaluate: '',
        isSubmitting: false,
        evaluationSubmitted: false,
        isUpdatingStatus: false
      }
    },
  
  async created() {
    const user = JSON.parse(localStorage.getItem('user') || 'null')
    if (!user) {
      location.hash = '#/login'
      return
    }
    
    // 从URL获取订单ID
    const orderId = this.$route.params.id
    if (orderId) {
      await this.loadOrderDetail(orderId)
    }
  },
  
  computed: {
    $route() {
      // 模拟Vue路由对象
      const hash = window.location.hash
      const parts = hash.split('/')
      // 确保URL格式正确并且有订单ID
      if (parts.length >= 3 && parts[1] === 'order') {
        return {
          params: {
            id: parts[2] // 格式为 #/order/123
          }
        }
      }
      return {
        params: {
          id: null
        }
      }
    }
  },
  
  methods: {
    goBack() {
      location.hash = '#/orders'
    },
    
    async loadOrderDetail(orderId) {
      // 验证订单ID是否有效
      if (!orderId || isNaN(orderId)) {
        this.error = '无效的订单ID'
        this.loading = false
        return
      }
      
      this.loading = true
      
      try {
        const res = await fetch(`/api/v1/orders/${orderId}`)
        if (res.ok) {
          this.orderDetail = await res.json()
          // 订单详情加载完成后，获取对应餐厅的菜单
          if (this.orderDetail && this.orderDetail.order) {
            // 获取餐厅信息（名称等）
            await this.loadRestaurantInfo(this.orderDetail.order.restaurantId)
            // 获取餐厅菜单（用于图片查询）
            await this.loadRestaurantMenu(this.orderDetail.order.restaurantId)
            // 根据商品名称更新图片URL
            this.updateImagesByMenuItemName()
            // 检查订单是否已评价
            await this.checkEvaluationStatus(orderId)
          }
        } else {
          alert('无法获取订单详情')
        }
      } catch (error) {
        alert('网络错误，请稍后再试')
      } finally {
        this.loading = false
      }
    },
    
    // 检查订单是否已评价
    async checkEvaluationStatus(orderId) {
      const user = JSON.parse(localStorage.getItem('user') || 'null')
      if (!user) return
      
      try {
        const res = await fetch(`/api/v1/orders/${orderId}/evaluate`)
        if (res.ok) {
          const evaluation = await res.json()
          if (evaluation && evaluation.id) {
            this.orderDetail.order.evaluationSubmitted = true
            this.orderDetail.order.score = evaluation.score
            this.orderDetail.order.evaluate = evaluation.content
            this.evaluationSubmitted = true
          }
        }
      } catch (error) {
        console.error('检查评价状态失败:', error)
      }
    },
    
    // 加载餐厅基本信息
    async loadRestaurantInfo(restaurantId) {
      if (!restaurantId) return
      
      try {
        const res = await fetch(`/api/v1/restaurants/${restaurantId}`)
        if (res.ok) {
          this.restaurant = await res.json()
        }
      } catch (error) {
        console.error('加载餐厅信息失败:', error)
      }
    },
    
    // 加载对应餐厅的菜单
    async loadRestaurantMenu(restaurantId) {
      if (!restaurantId) return
      
      try {
        const res = await fetch(`/api/v1/restaurants/${restaurantId}/menu`)
        if (res.ok) {
          this.menuItems = await res.json()
        }
      } catch (error) {
        console.error('加载餐厅菜单失败:', error)
      }
    },
    
    // 根据商品名称从菜单中查询并更新图片URL
    updateImagesByMenuItemName() {
      if (!this.orderDetail || !this.orderDetail.items || this.menuItems.length === 0) return
      
      this.orderDetail.items.forEach(item => {
        // 根据商品名称在菜单中查找对应项
        const menuItem = this.menuItems.find(menuItem => menuItem.name === item.menuItemName)
        // 如果找到匹配项，更新图片URL
        if (menuItem && menuItem.imageUrl) {
          item.imageUrl = menuItem.imageUrl
        }
      })
    },
    
    canCancelOrder(order) {
      // 只有状态为pending的订单才可能被取消
      if (order.status !== 'pending') {
        return false
      }
      
      // 检查订单是否在一分钟内创建
      const orderDate = new Date(order.orderDate)
      const now = new Date()
      const minutesDiff = (now - orderDate) / (1000 * 60)
      
      return minutesDiff < 1
    },
    
    // 判断订单是否可以更新状态
    canUpdateOrderStatus(order) {
      // 只有状态为pending的订单才可以更新为completed
      return order.status === 'pending'
    },
    
    // 更新订单状态
    async updateOrderStatus() {
      const user = JSON.parse(localStorage.getItem('user') || 'null')
      if (!user) {
        location.hash = '#/login'
        return
      }
      
      this.isUpdatingStatus = true
      
      try {
        const orderId = this.orderDetail.order.id
        const res = await fetch(`/api/v1/orders/${orderId}/status?userId=${user.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ newStatus: 'completed' })
        })
        
        if (res.ok) {
          // 成功更新状态后，重新加载订单详情
          await this.loadOrderDetail(orderId)
          alert('订单状态已更新为已完成')
        } else {
          const errorMsg = await res.text()
          alert(errorMsg || '更新订单状态失败')
        }
      } catch (error) {
        console.error('更新订单状态失败:', error)
        alert('网络错误，请稍后再试')
      } finally {
        this.isUpdatingStatus = false
      }
    },
    
    // 判断订单是否可以评价
    canEvaluateOrder(order) {
      // 只有状态为completed（已完成）且未评价的订单才可以评价
      return order.status === 'completed' && !order.evaluate && !order.evaluationSubmitted
    },
    
    // 提交订单评价
    async submitEvaluation() {
      const user = JSON.parse(localStorage.getItem('user') || 'null')
      if (!user) {
        location.hash = '#/login'
        return
      }
      
      // 验证评价内容
      if (!this.evaluate.trim()) {
        alert('请输入评价内容')
        return
      }
      
      this.isSubmitting = true
      
      try {
        const orderId = this.orderDetail.order.id
        const res = await fetch(`/api/v1/orders/${orderId}/evaluate`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userId: user.id,
            content: this.evaluate,
            score: this.score
          })
        })
        
        if (res.ok) {
          alert('评价提交成功')
          this.evaluationSubmitted = true
          // 更新订单详情，显示评价内容
          await this.loadOrderDetail(orderId)
        } else {
          const errorMsg = await res.text()
          alert(errorMsg || '评价提交失败，请稍后再试')
        }
      } catch (error) {
        alert('网络错误，请稍后再试')
        console.error('提交评价失败:', error)
      } finally {
        this.isSubmitting = false
      }
    },
    
    async cancelOrder(orderId) {
      const user = JSON.parse(localStorage.getItem('user') || 'null')
      if (!user) {
        location.hash = '#/login'
        return
      }
      
      if (confirm('确定要取消此订单吗？')) {
        try {
          const res = await fetch(`/api/v1/orders/${orderId}/cancel?userId=${user.id}`, {
            method: 'PUT'
          })
          
          if (res.ok) {
            alert('订单已成功取消')
            await this.loadOrderDetail(orderId) // 重新加载订单详情
          } else {
            const errorMsg = await res.text()
            alert(errorMsg || '取消订单失败，请稍后再试')
          }
        } catch (error) {
          alert('网络错误，请稍后再试')
        }
      }
    },
    
    formatOrderDate(dateString) {
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>